/*
 * Copyright 2012 ron-ang-code Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ron.ang.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * This code requires SuperCSV-1.52.jar and the android.jar to compile
 */
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.prefs.CsvPreference;

import android.content.ContentValues;

/**
 * 
 * @author Ronillo Ang
 */
public class DataExporter {

	/**
	 * 
	 * @param header the column header
	 * @param dataList the list of data to be exported
	 * @param file data will be written to this specified file
	 * @throws IOException if an I/O error occurs
	 */
	public void writeToCsv(String[] header, List<? extends Data> dataList,
			File file) throws IOException {
		ICsvMapWriter writer = new CsvMapWriter(new FileWriter(file),
				CsvPreference.EXCEL_PREFERENCE);

		try {
			if (!dataList.isEmpty() && header != null) {
				writer.writeHeader(header);
			}

			for (Data dataObject : dataList) {
				ContentValues cv = dataObject.toCSV();
				Map<String, ? super Object> data = new HashMap<String, Object>();

				for (String key : header) {
					Object value = cv.get(key);
					data.put(key, value);
				}

				writer.write(data, header);
			}
		} finally {
			writer.close();
		}

	}
}
